// Copyright (c) 2021 Presto Labs Pte. Ltd.
// Author: daniel

#pragma once

#include <memory>
#include <optional>
#include <string>
#include <vector>

#include "coin2/exchange/base/symbology/spot_product.h"
#include "coin2/exchange/base/symbology/util.h"
#include "coin2/exchange/gopax/symbology/currency.h"

namespace coin2::exchange::gopax::symbology {

class GopaxProduct : public base::symbology::SpotProduct<GopaxCurrency, GopaxProduct>,
                     public base::symbology::ProductFromStrMixin<GopaxProduct> {
 public:
  typedef SpotProduct<GopaxCurrency, GopaxProduct> BaseProduct;

  GopaxProduct(const GopaxCurrency& base, const GopaxCurrency& quote)
      : SpotProduct(
            base,
            quote,
            ToGopaxOrderNativeProduct(base, quote),
            ToGopaxFeedNativeProduct(base, quote),
            base::market::ExchangeType::Gopax) {}

 public:
  static std::unique_ptr<GopaxProduct> FromNativeStrImpl(
      const std::string& native_product,
      int64_t resolve_timestamp) {
    std::unique_ptr<GopaxCurrency> base_ptr;
    std::unique_ptr<GopaxCurrency> quote_ptr;
    bool success =
        ParseGopaxNativeProduct(native_product, resolve_timestamp, &base_ptr, &quote_ptr);
    if (success) {
      return std::make_unique<GopaxProduct>(*base_ptr, *quote_ptr);
    } else {
      return {};
    }
  }

 private:
  static bool ParseGopaxNativeProduct(
      const std::string& product_str,
      int64_t resolve_timestamp,
      std::unique_ptr<GopaxCurrency>* base_ptr,
      std::unique_ptr<GopaxCurrency>* quote_ptr) {
    const std::string& product_str_upper = StringToUpperCopy(product_str);
    std::string currency_base = product_str_upper;
    std::string currency_quote = "KRW";
    if (auto pos = product_str.find('-'); pos != std::string::npos) {
      std::vector<std::string> splitted;
      splitted = Split(product_str_upper, "-");
      currency_base = splitted[0];
      currency_quote = splitted[1];
    }
    *base_ptr = GopaxCurrency::FromNativeStrNoThrow(currency_base, resolve_timestamp);
    *quote_ptr = GopaxCurrency::FromNativeStrNoThrow(currency_quote, resolve_timestamp);
    return true;
  }

  static std::string ToGopaxOrderNativeProduct(
      const GopaxCurrency& base,
      const GopaxCurrency& quote) {
    using base::market::MarketType;
    std::stringstream ss;
    ss << base.native_currency(MarketType::Spot) << '-' << quote.native_currency(MarketType::Spot);
    auto native_product_str = ss.str();
    return native_product_str;
  }

  static std::string ToGopaxFeedNativeProduct(
      const GopaxCurrency& base,
      const GopaxCurrency& quote) {
    using base::market::MarketType;
    std::stringstream ss;
    ss << base.native_currency(MarketType::Spot) << '-' << quote.native_currency(MarketType::Spot);
    auto native_product_str = ss.str();
    return native_product_str;
  }
};

}  // namespace coin2::exchange::gopax::symbology
